﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace DARE
{
    [AttrTypeDependentSerializable(typeof(CControllerData))]
    public class CController: CComponent
    {
        #region fields

        private CCharacterController m_characterController;

        #endregion

        #region properties

        [ContentSerializerIgnore]
        public CCharacterController CharacterController { get { if (m_characterController == null) m_characterController = new CCharacterController(); return m_characterController; } }
        [ContentSerializerIgnore]
        public override CGameObject GameObject
        {
            get
            {
                return base.GameObject;
            }
            set
            {
                if (m_gameObject != value && m_gameObject != null)
                {
                    m_gameObject.OnUpdate -= OnUpdate;
                }
                base.GameObject = value;
                if (m_gameObject != null)
                {
                    m_gameObject.OnUpdate -= OnUpdate;
                    m_gameObject.OnUpdate += OnUpdate;

                    float speed = 0;
                    if (m_characterController != null)
                    {
                        speed = m_characterController.MoveSpeed;
                        m_characterController.DisableController();
                    }
                    m_characterController = new CCharacterController(m_gameObject.Node);
                    m_characterController.MoveSpeed = speed;
                }
            }
        }

        #endregion

        #region ctor

        public CController()
        {
           
        }

        #endregion

        #region methods

        public override CComponent Clone(CGameObject gameObject)
        {
            CController cont = new CController();
            cont.GameObject = gameObject;
            cont.m_characterController.MoveSpeed = m_characterController.MoveSpeed;
            return cont;
        }

        public void OnUpdate(CGameObject gameObject)
        {
            if (m_characterController == null)
                return;
            m_gameObject.Node.Entity.Physic.Body.MoveTo(m_gameObject.Node.Position, Matrix.CreateFromYawPitchRoll(m_characterController.YawDirection + MathHelper.ToRadians(90), 0, 0));
            //m_gameObject.Node.IgnorePhysicsTransform = true;
            //m_gameObject.Node.SetOrientation(Quaternion.CreateFromYawPitchRoll(m_characterController.YawDirection+MathHelper.ToRadians(90), 0, 0));
            //m_gameObject.Node.IgnorePhysicsTransform = false;
        }

        #endregion
    }
}
